<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="摄像头编号" prop="cameraCode">
        <el-input
          v-model="queryParams.cameraCode"
          placeholder="请输入定点摄像头编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="边坡名称" prop="slopeCode">
        <el-select v-model="queryParams.slopeCode" placeholder="请选择边坡名称" clearable style="width: 180px">
          <el-option
            v-for="dict in slopeCodeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="监测区域" prop="monitorArea">
        <el-select v-model="queryParams.monitorArea" placeholder="请选择监测区域" clearable style="width: 180px">
          <el-option
            v-for="dict in monitor_area"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['video:camera:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['video:camera:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['video:camera:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['video:camera:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cameraList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="定点摄像头编号" align="center" prop="cameraCode" />
      <el-table-column label="边坡名称" align="center" prop="slopeCode">
        <template #default="scope">
          <dict-tag :options="slopeCodeList" :value="scope.row.slopeCode"/>
        </template>
      </el-table-column>
      <el-table-column label="摄像头状态" align="center" prop="cameraStatus">
        <template #default="scope">
          <dict-tag :options="sensor_data_status" :value="scope.row.cameraStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="监测区域" align="center" prop="monitorArea">
        <template #default="scope">
          <dict-tag :options="monitor_area" :value="scope.row.monitorArea"/>
        </template>
      </el-table-column>
      <el-table-column label="视频流链接" align="center" prop="videoUrl">
        <template #default="scope">
          <a :href="scope.row.videoUrl" target="_blank" style="color: #409EFF; text-decoration: underline;">
            {{ scope.row.videoUrl }}
          </a>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['video:camera:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['video:camera:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改定点摄像头对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="cameraRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="摄像头编号" prop="cameraCode">
          <el-input v-model="form.cameraCode" placeholder="请输入定点摄像头编号" />
        </el-form-item>
        <el-form-item label="摄像头状态" prop="cameraStatus">
          <el-select v-model="form.cameraStatus" placeholder="请选择摄像头状态">
            <el-option
                v-for="dict in sensor_data_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="边坡名称" prop="slopeCode">
          <el-select v-model="form.slopeCode" placeholder="请选择边坡名称">
            <el-option
              v-for="dict in slopeCodeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="监测区域" prop="monitorArea">
          <el-select v-model="form.monitorArea" placeholder="请选择监测区域">
            <el-option
              v-for="dict in monitor_area"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="视频流链接" prop="videoUrl">
          <el-input v-model="form.videoUrl" type="textarea" placeholder="请输入内容" />
          <br/>
          <el-button
              type="primary"
              style="margin-left: 120px; margin-top: 10px"
              :disabled="!form.cameraCode"
              @click="fetchVideoUrl"
          >
            获取链接
          </el-button>
        </el-form-item>
        <el-form-item label="管养单位" prop="deptId">
          <el-select v-model="form.deptId" placeholder="请选择管养单位">
            <el-option
              v-for="dict in sys_dept_list"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Camera">
import { listCamera, getCamera, delCamera, addCamera, updateCamera } from "@/api/slope/video/camera";
import { listSlopeCode } from "@/api/slope/info/info.js"
import { ElMessage, ElMessageBox } from 'element-plus';
import { reactive } from 'vue';

const slopeCodeList = ref([])
const { proxy } = getCurrentInstance();
const { sys_dept_list, monitor_area, sensor_data_status } = proxy.useDict('sys_dept_list', 'monitor_area', 'sensor_data_status');

const cameraList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cameraCode: null,
    slopeCode: null,
    monitorArea: null,
  },
  rules: {
    cameraCode: [
      { required: true, message: "摄像头ID不能为空", trigger: "blur" }
    ],
    slopeCode: [
      { required: true, message: "边坡名称不能为空", trigger: "change" }
    ],
    deptId: [
      { required: true, message: "管养单位不能为空", trigger: "change" }
    ],
    monitorArea: [
      { required: true, message: "监测区域不能为空", trigger: "change" }
    ],
    videoUrl:[
        { required: true, message: "视频流链接不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

const fetchVideoUrl = async () => {
  if (!form.value.cameraCode) {
    console.warn('摄像头编号未填写');
    ElMessage.warning('请填写摄像头编号');
    return;
  }

  const deviceSerial = form.value.cameraCode;

  try {
    // ① 用 GET 请求，URL 直接拼接参数获取 token
    const tokenUrl = `https://open.ys7.com/api/lapp/token/get?appKey=33fbe49312e24bb4b0b0fe0c65402e78&appSecret=112acee14c43707ecd9413cb6e8514b6`;

    const tokenRes = await fetch(tokenUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    });

    const tokenData = await tokenRes.json();

    if (tokenData.code !== '200') {
      await ElMessageBox.alert(
          `Token 获取失败<br>错误代码：${tokenData.code}<br>错误信息：${tokenData.msg || '未知错误'}`,
          '请求失败',
          {
            dangerouslyUseHTMLString: true,
            type: 'error',
            confirmButtonText: '确定'
          }
      );
      return;
    }

    const token = tokenData.data.accessToken;

    // ② 用 token 请求视频地址接口（保持 POST JSON 请求）
    const requestUrl = `https://open.ys7.com/api/lapp/v2/live/address/get?accessToken=${token}&deviceSerial=${deviceSerial}`;

    const response = await fetch(requestUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    });

    const res = await response.json();

    if (res.code === '200' && res.data?.url) {
      const videoUrl = `https://open.ys7.com/console/jssdk/pc.html?accessToken=${token}&url=${res.data.url}`;
      form.value.videoUrl = videoUrl;
      ElMessage.success('视频链接获取成功');
    } else {
      form.value.videoUrl = `错误代码：${res.code},错误信息：${res.msg || '未知错误'}`;
      await ElMessageBox.alert(
          `错误代码：${res.code}<br>错误信息：${res.msg || '未知错误'}`,
          '视频链接获取失败',
          {
            dangerouslyUseHTMLString: true,
            type: 'error',
            confirmButtonText: '确定'
          }
      );
    }
  } catch (err) {
    await ElMessageBox.alert(
        `请求过程中发生错误：${err.message}`,
        '请求异常',
        {
          type: 'error',
          confirmButtonText: '确定'
        }
    );
  }
};




/** 查询定点摄像头列表 */
function getList() {
  loading.value = true;
  listSlopeCode().then(response => {
    // 假设 response 是一个普通的对象
    slopeCodeList.value = Object.entries(response).map(([key, value]) => ({
      label: key,
      value: value
    }))
  })
  listCamera(queryParams.value).then(response => {
    cameraList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    cameraCode: null,
    slopeCode: null,
    cameraStatus: null,
    monitorArea: null,
    videoUrl: null,
    deptId: null
  };
  proxy.resetForm("cameraRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加定点摄像头";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCamera(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改定点摄像头";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["cameraRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCamera(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCamera(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除定点摄像头编号为"' + _ids + '"的数据项？').then(function() {
    return delCamera(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('video/camera/export', {
    ...queryParams.value
  }, `camera_${new Date().getTime()}.xlsx`)
}

getList();
</script>
